package com.beimi.net;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;

import com.corundumstudio.socketio.AuthorizationListener;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;

@org.springframework.context.annotation.Configuration
public class SocketIOConf {

	@Value("${uk.im.server.port}")
	private Integer port;

	@Bean
	public SocketIOServer socketIOServer() {
		Configuration config = new Configuration();
		// config.setHostname("localhost");
		config.setPort(port);
		config.setSocketConfig(new SocketConfig());
		// config.setOrigin("http://im.ukewo.com");

		config.setWorkerThreads(100);
		// config.setStoreFactory(new HazelcastStoreFactory());
		config.setAuthorizationListener(new AuthorizationListener() {

			public boolean isAuthorized(HandshakeData data) {
				return true;
			}
		});

		SocketIOServer server = new SocketIOServer(config);
		server.addNamespace("/bm/game");
		return server;
	}

	@Bean
	public EmbeddedServletContainerCustomizer containerCustomizer() {

		return new EmbeddedServletContainerCustomizer() {
			@Override
			public void customize(ConfigurableEmbeddedServletContainer container) {

				ErrorPage error = new ErrorPage("/error.html");

				container.addErrorPages(error);
			}
		};
	}

	@Bean
	public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
		return new SpringAnnotationScanner(socketServer);
	}
}
